#include <stdio.h>
#include <jni.h>
#include <string.h>

JNIEnv* create_vm(JavaVM ** jvm) {
	JNIEnv *env;
	JavaVMInitArgs vm_args;
	JavaVMOption options;
	options.optionString =
			"-Djava.class.path=../target/PFSBuilder-20140619.jar";
	vm_args.version = JNI_VERSION_1_6;
	vm_args.nOptions = 1;
	vm_args.options = &options;
	vm_args.ignoreUnrecognized = 0;

	JNI_CreateJavaVM(jvm, (void**) &env, &vm_args);
	return env;
}

int main(int argc, char* argv[]) {
	JNIEnv *env;
	JavaVM * jvm;
	env = create_vm(&jvm);
	jclass cls = (*env)->FindClass(env, "com/pfsbuilder/fuse/FuseStub");
	if (cls == 0) {
		printf("load class error\n");
		exit(-1);
	}

	// test 1
	jmethodID test1 = (*env)->GetStaticMethodID(env, cls, "test1",
			"(Ljava/lang/String;)Ljava/lang/String;");
	if (test1 == 0) {
		printf("load test1 error\n");
		exit(-1);
	}
	jstring para1 = (*env)->NewStringUTF(env, "Peter cheung");
	jstring returnString1 = (jstring)(*env)->CallStaticObjectMethod(env, cls,
			test1, para1);
	printf("return=%s\n", (*env)->GetStringUTFChars(env, returnString1, 0));

	// test 2
	jmethodID test2 = (*env)->GetStaticMethodID(env, cls, "test2",
			"(Ljava/lang/String;)[Ljava/lang/String;");
	if (test2 == 0) {
		printf("load test2 error\n");
		exit(-1);
	}
	jstring para2 = (*env)->NewStringUTF(env, "Peter cheung");
	jobjectArray returnArray2 = (jstring)(*env)->CallStaticObjectMethod(env,
			cls, test2, para2);
	int len = (*env)->GetArrayLength(env, returnArray2);
	int x;
	for (x = 0; x < len; x++) {
		jobject obj = (*env)->GetObjectArrayElement(env, returnArray2, x);
		printf("return=%s\n", (*env)->GetStringUTFChars(env, obj, 0));
	}

	// readdir
	jmethodID readdir = (*env)->GetStaticMethodID(env, cls, "readdir",
			"(Ljava/lang/String;)V");
	if (readdir == 0) {
		printf("load readdir error\n");
		exit(-1);
	}
	jstring paraReadDir = (*env)->NewStringUTF(env, "Peter cheung");
	(*env)->CallStaticVoidMethod(env, cls, readdir, paraReadDir);
//	int len = (*env)->GetArrayLength(env, returnArray2);
//	int x;
//	for (x = 0; x < len; x++) {
//		jobject obj = (*env)->GetObjectArrayElement(env, returnArray2, x);
//		printf("return=%s\n", (*env)->GetStringUTFChars(env, obj, 0));
//	}

	return 0;
}
